﻿@page "/settlement-service"
@rendermode InteractiveServer

@using BlazorAutoEx
@using BlazorAutoEx.Models
@using BlazorAutoEx.Services
@using Microsoft.Extensions.Options

@inject SettlementService BackgroundService
@inject ILogger<SettlementService> Logger

<h3 style="color:#113399">自动结算服务</h3>


<div>


    <!-- 系统状态监视器 -->
    <div class="status-monitor compact-section" style="@运行状态底色()">
        <div class="status-item" >
            <div class="status-icon">
                <img src="/image/b_power.svg" width="18" class="bi" aria-hidden="true" />
            </div>
            <div class="status-text">
                <h3>自动扣款系统状态</h3>
                <p style="@运行状态字色()">@运行状态()</p>
            </div>
        </div>

        <div class="status-item">
            <div class="status-icon">
                <img src="/image/b_list-check.svg" width="18" class="bi" aria-hidden="true" />
            </div>
            <div class="status-text">
                <h3>设置号：@timeSerCon.Id</h3>
                <p>@timeSerCon.Name</p>
            </div>
        </div>

        <div class="status-item">
            <div class="status-icon">
                <img src="/image/b_arrow-repeat.svg" width="18" class="bi" aria-hidden="true" />
            </div>
            <div class="status-text">
                <h3>最后执行时间</h3>
                <p>@Program.lastTime</p>
            </div>
        </div>


        <div class="status-item">
            <div class="status-icon">
                <img src="/image/b_clock-history.svg" width="18" class="bi" aria-hidden="true" />
            </div>
            <div class="status-text">
                <h3>下次执行</h3>
                <p>@Program.nextTime</p>
            </div>
        </div>
    </div>


    <div class="dashboard">
        <!-- 自动扣款设置面板 -->
        <div class="panel compact-panel">
            <div class="panel-header">
                <i class="fas fa-cog"></i>
                <span>自动扣款设置</span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label class="compact-title">结算多久以前的订单：</label>
                    <div class="time-inputs">
                        <div class="time-input">
                            <input type="number" id="days" min="0" @bind="timeSerCon.SetDay">
                            <span>天</span>
                        </div>
                        <div class="time-input">
                            <input type="number" id="hours" min="0" max="23" @bind="timeSerCon.SetHour">
                            <span>小时</span>
                        </div>
                        <div class="time-input">
                            <input type="number" id="minutes" min="0" max="59" @bind="timeSerCon.SetMinute">
                            <span>分钟</span>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="compact-title">执行频率设置：</label>
                    <div class="row">
                        <div class="col-lg-4 mb-3">
                            <div class="option-card">
                                <div class="option-header">
                                    <input type="radio" id="frequency-immediate" name="frequency" @onchange="@(() => selectedValue = 1)" checked="@(selectedValue == 1)">
                                    <label for="frequency-immediate">立即执行一次</label>
                                </div>
                                <div class="option-content">
                                    <p>启动后立即执行一次扣款操作，执行好后停止运行</p>
                                </div>
                            </div>

                        </div>

                        <div class="col-lg-4 mb-3">
                            <div class="option-card">
                                <div class="option-header">
                                    <input type="radio" id="frequency-interval" name="frequency" @onchange="@(() => selectedValue = 2)" checked="@(selectedValue == 2)">
                                    <label for="frequency-interval">间隔执行</label>
                                </div>
                                <div class="option-content">
                                    <div class="time-inputs">
                                        <div>
                                            <span>每</span>
                                        </div>
                                        <div class="time-input">
                                            <input type="number" id="interval-value" min="0" @bind="timeSerCon.ExeHour">
                                            <span>小时</span>
                                        </div>
                                        <div class="time-input">
                                            <input type="number" id="interval-value" min="0" @bind="timeSerCon.ExeMinute">
                                            <span>分</span>
                                        </div>
                                        <div class="time-input">
                                            <input type="number" id="interval-value" min="0" @bind="timeSerCon.ExeSecond">
                                            <span>秒</span>
                                        </div>
                                        <div>
                                            <span>执行一次</span>
                                        </div>

                                    </div>
                                </div>
                            </div>

                        </div>

                        <div class="col-lg-4 mb-3">
                            <div class="option-card">
                                <div class="option-header">
                                    <input type="radio" id="frequency-daily" name="frequency" @onchange="@(() => selectedValue = 3)" checked="@(selectedValue == 3)">
                                    <label for="frequency-daily">每日定时执行</label>
                                </div>
                                <div class="option-content">
                                    <p>每天在以下时间点执行扣款操作：</p>
                                    <div class="time-slots">

                                        @foreach (var fore in TimeAutoSetList)
                                            {
                                                <div class="time-slot">
                                                    <input type="time" class="daily-time" @bind="fore.ExeTimeOnly" @bind:after="@(() => 更新时间(fore))">
                                                    <button class="btn remove-time" @onclick="() => 删除时间(fore)">
                                                        <img src="/image/red-x.svg" width="14" class="bi img-up" aria-hidden="true" alt="x" />
                                                    </button>
                                                </div>
                                            }

                                    </div>
                                    <button class="add-time-btn" @onclick="新建每日执行时间">
                                        <img src="/image/svg-white/White_plus.svg" width="16" class="bi img-up" aria-hidden="true" alt="+" />
                                        添加执行时间
                                    </button>
                                    <button class="add-time-btn" @onclick="排序时间">
                                        <img src="/image/svg-white/White_arrow-couterclockwise.svg" width="16" class="bi img-up" aria-hidden="true" alt=">" />
                                        排序
                                    </button>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

                <div class="action-buttons">
                    <button class="btn btn-save" @onclick="SaveConfig">
                        <img src="/image/svg-white/White_pencil-square-fill.svg" width="16" class="bi" aria-hidden="true" />
                        保存配置
                    </button>
                    <button class="btn btn-start" @onclick="启动" disabled="@cisRun">
                        <img src="/image/svg-white/White_play-fill.svg" width="16" class="bi" aria-hidden="true" />
                        启动自动扣款
                    </button>
                    <button class="btn btn-stop" @onclick="停止" disabled="@(!cisRun)">
                        <img src="/image/svg-white/White_stop-fill.svg" width="16" class="bi" aria-hidden="true" />
                        停止
                    </button>
                </div>
            </div>
        </div>

        <!-- 手动扣款面板 -->
        <div class="panel compact-panel">
            <div class="panel-header">
                <i class="fas fa-search-dollar"></i>
                <span>工单查询与手动扣款</span>
            </div>
            <div class="panel-body">
                <div class="search-form">
                    <div>
                        <label for="customer-id">客户ID/名称</label>
                        <input type="text" id="customer-id" class="form-control" placeholder="输入客户ID或名称">
                    </div>

                    <div>
                        <label for="date-range">时间范围</label>
                        <div style="display: flex; gap: 10px;">
                            <input type="date" id="start-date" class="form-control" value="2023-07-01">
                            <input type="date" id="end-date" class="form-control" value="2023-07-25">
                        </div>
                    </div>

                    <button class="btn btn-search">
                        <i class="fas fa-search"></i> 查询工单
                    </button>
                </div>

                <table class="results-table">
                    <thead>
                        <tr>
                            <th style="width: 30px;"><input type="checkbox" id="select-all"></th>
                            <th>工单编号</th>
                            <th>客户名称</th>
                            <th>工单金额</th>
                            <th>创建时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="checkbox" class="order-checkbox"></td>
                            <td>ORD-20230725-001</td>
                            <td>张明科技有限公司</td>
                            <td>¥8,500.00</td>
                            <td>2023-07-22 10:30</td>
                            <td><span class="status-badge status-pending">待扣款</span></td>
                            <td><button class="action-btn">扣款</button><button class="action-btn">详情</button></td>

                        </tr>
                        <tr>
                            <td><input type="checkbox" class="order-checkbox" checked></td>
                            <td>ORD-20230724-045</td>
                            <td>李华商贸有限公司</td>
                            <td>¥12,300.00</td>
                            <td>2023-07-20 14:15</td>
                            <td><span class="status-badge status-success">已扣款</span></td>
                            <td><button class="action-btn">退款</button><button class="action-btn">详情</button></td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="order-checkbox"></td>
                            <td>ORD-20230723-128</td>
                            <td>王强物流服务</td>
                            <td>¥5,200.50</td>
                            <td>2023-07-18 16:45</td>
                            <td><span class="status-badge status-pending">待扣款</span></td>
                            <td><button class="action-btn">扣款</button><button class="action-btn">详情</button></td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="order-checkbox"></td>
                            <td>ORD-20230722-087</td>
                            <td>陈晓教育咨询</td>
                            <td>¥3,800.00</td>
                            <td>2023-07-15 09:20</td>
                            <td><span class="status-badge status-failed">扣款失败</span></td>
                            <td><button class="action-btn">重试</button><button class="action-btn">详情</button></td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="order-checkbox"></td>
                            <td>ORD-20230721-056</td>
                            <td>刘芳设计工作室</td>
                            <td>¥6,750.00</td>
                            <td>2023-07-10 11:05</td>
                            <td><span class="status-badge status-pending">待扣款</span></td>
                            <td><button class="action-btn">扣款</button><button class="action-btn">详情</button></td>
                        </tr>
                    </tbody>
                </table>

                <div class="batch-actions">
                    <div class="select-info">
                        已选择 <span id="selected-count">0</span> 个工单
                    </div>
                    <button class="btn btn-batch">
                        <i class="fas fa-money-bill-wave"></i> 批量扣款
                    </button>
                </div>
            </div>
        </div>
    </div>



</div>


<script>
    // 简单的标签页切换效果增强
    document.addEventListener('DOMContentLoaded', function() {
        const tabLinks = document.querySelectorAll('#rechargeTab .nav-link');

        tabLinks.forEach(link => {
            link.addEventListener('click', function() {
                tabLinks.forEach(l => l.classList.remove('active'));
                this.classList.add('active');
            });
        });
    });
</script>

@code {

    public TimedSerCfgdb? timeSerCon;
    public List<TimeAutoSet> TimeAutoSetList =[];
    public string? logs;

    // 选中的值
    private int selectedValue { get; set; } = 1;

    bool cisRun = false;
    private string 运行状态()
    {
        if (cisRun)
        {
            return "运行中";
        }
        else
        {
            return "已停止";
        }
    }
    private string 运行状态字色()
    {
        if (cisRun)
        {
            return "color:#11aa00";
        }
        else
        {
            return "color:#ee2233";
        }
    }
    private string 运行状态底色()
    {
        if (cisRun)
        {
            return "background-color:#ccffcc";
        }
        else
        {
            return "background-color:#ffbbbb";
        }
    }

    protected override async Task OnInitializedAsync()
    {

        //加载数据
        TimeAutoSetList = Dbcon.db.Queryable<TimeAutoSet>().OrderBy(it => it.ExeTime).ToList();

        timeSerCon = Dbcon.db.Queryable<TimedSerCfgdb>().First();

        selectedValue = timeSerCon.ExecuteSet ?? 1;

        Program.lastTime = timeSerCon.LastTime;
        Program.nextTime = timeSerCon.NextTime;

        cisRun = BackgroundService.IsRunning;
        await InvokeAsync(StateHasChanged);
    }


    private void 新建每日执行时间()
    {
        var ddd = Dbcon.db.Insertable(new TimeAutoSet() { ExeTimeOnly = new(23, 59, 59) }).ExecuteReturnEntity();
        TimeAutoSetList.Add(ddd);
    }
    private void 更新时间(TimeAutoSet p)
    {
        Dbcon.db.Updateable(p).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
    }
    private void 删除时间(TimeAutoSet p)
    {
        Dbcon.db.Deleteable<TimeAutoSet>(new TimeAutoSet() { Id = p.Id }).ExecuteCommand();
        TimeAutoSetList.RemoveAll(it => it.Id == p.Id);
    }
    private void 排序时间()
    {
        TimeAutoSetList.Sort((a, b) => a.ExeTime.CompareTo(b.ExeTime));
    }


    private void SaveConfig()
    {

        timeSerCon.ExecuteSet = selectedValue;
        // 更新配置到数据库
        Dbcon.db.Updateable(timeSerCon).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();

    }

    private async Task 启动()
    {
        if (selectedValue == 1)
        {
            SaveConfig();

            cisRun = true;

            // 运行扣款程序
            await exe.模拟程序执行();

            cisRun = false;
            StateHasChanged(); // 立即刷新UI
            return;
        }
        if (selectedValue == 2)
        {
            timeSerCon.ExTimeSec = timeSerCon.ExeTime / (double)TimeSpan.TicksPerSecond;
            Program.timeSpan = timeSerCon.ExTimeSec ?? 28800;
            Program.lastTime = DateTime.Now;
            Program.nextTime = DateTime.Now.AddSeconds(Program.timeSpan);
            timeSerCon.LastTime = Program.lastTime;
            timeSerCon.NextTime = Program.nextTime;
            timeSerCon.ExecuteSet = selectedValue;
            Dbcon.db.Updateable(timeSerCon).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();

            //启动服务
            try
            {
                BackgroundService.StartService(2);
                logs=($"间隔执行服务已启动于: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                Logger.LogInformation("用户启动了后台间隔执行服务");
                cisRun = true;
                await WriteToFileAsync(logs);
            }
            catch (Exception ex)
            {
                logs = ($"启动间隔执行服务失败: {ex.Message}");
                Logger.LogError(ex, "启动间隔执行服务时发生错误");
                await WriteToFileAsync(logs);
            }

        }
        if (selectedValue == 3)
        {
            DateTime now = DateTime.Now;
            var timeList = Dbcon.db.Queryable<TimeAutoSet>().ToList().OrderBy(it => it.ExeTime);
            var time = timeList
                .Select(it => (TimeSpan?)it.ExeTimeOnly.ToTimeSpan())
                .FirstOrDefault(it => it > now.TimeOfDay, null);
            if (time is not null)
            {
                //算出时间差
                DateTime newDateWithMidnight = now.Date + time.Value;
                timeSerCon.ExTimeSec = (newDateWithMidnight - now).TotalSeconds;
               
            }
            else if (timeList.Any())
            {
                //算出明天第一个时间与现在之间的时间差
                DateTime newDateWithMidnight = now.Date.AddDays(1) + (timeList.First()?.ExeTimeOnly.ToTimeSpan() ?? TimeSpan.Zero);
                timeSerCon.ExTimeSec = (newDateWithMidnight - now).TotalSeconds;
              
            }

            Program.timeSpan = timeSerCon.ExTimeSec ?? 28800;
            Program.lastTime = now;
            Program.nextTime = now.AddSeconds(Program.timeSpan);
            timeSerCon.LastTime = Program.lastTime;
            timeSerCon.NextTime = Program.nextTime;
            timeSerCon.ExecuteSet = selectedValue;
            Dbcon.db.Updateable(timeSerCon).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();

            //启动服务
            try
            {
                BackgroundService.StartService(3);
                logs = ($"定时执行服务已启动于: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                Logger.LogInformation("用户启动了后台定时执行服务");
                cisRun = true;
                await WriteToFileAsync(logs);
            }
            catch (Exception ex)
            {
                logs = ($"启动定时执行服务失败: {ex.Message}");
                Logger.LogError(ex, "启动定时执行服务时发生错误");
                await WriteToFileAsync(logs);
            }

        }
    }

    private async Task 停止()
    {
        try
        {
            BackgroundService.StopService();
            logs=($"服务已停止于: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            Logger.LogInformation("用户停止了后台服务");
            cisRun = false;
            await WriteToFileAsync(logs);
        }
        catch (Exception ex)
        {
            logs=($"停止服务失败: {ex.Message}");
            Logger.LogError(ex, "停止服务时发生错误");
            await WriteToFileAsync(logs);
        }
    }

    private async Task WriteToFileAsync(string message)
    {
       
        //写入文件
        var content = $"{DateTime.Now}: {message}";
        var filePath = Path.Combine(BackgroundService.Env.ContentRootPath, "logs.txt");

        await File.AppendAllLinesAsync(filePath, new[] { content });
    }



}